<script setup lang="ts">
import { ref, watchEffect } from 'vue';

import { ossInfo } from '#/api/system/oss';

const props = defineProps({
  ossid: {
    type: String,
    required: true,
  },
});

const imageUrl = ref('');
const isLoading = ref(true);

watchEffect(async () => {
  if (props.ossid) {
    isLoading.value = true;
    imageUrl.value = ''; // Reset image url while loading new one
    try {
      const res = await ossInfo([props.ossid]);
      if (res && res.length > 0 && res[0]?.url) {
        imageUrl.value = res[0].url;
      } else {
        // console.warn(`未找到 ossid: ${props.ossid} 对应的图片URL`);
      }
    } catch (error) {
      console.error(`获取 ossid ${props.ossid} 图片信息失败:`, error);
    } finally {
      isLoading.value = false;
    }
  } else {
    imageUrl.value = '';
    isLoading.value = false;
  }
});

const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement;
  target.style.display = 'none'; // 例如，隐藏损坏的图片
  // 或者可以显示一个占位符: target.src = 'path/to/fallback-image.png';
};
</script>

<template>
  <span v-if="isLoading">加载中...</span>
  <img
    v-else-if="imageUrl"
    :src="imageUrl"
    :style="{
      width: '50px',
      height: '50px',
      objectFit: 'contain',
      display: 'block',
      margin: 'auto',
    }"
    @error="handleImageError"
  />
  <span v-else></span>
</template>
